package com.nf.mvc.argument;

import com.nf.mvc.MethodArgumentResolver;
import com.nf.mvc.util.ClassUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

import static com.nf.mvc.ioc.BeanFactory.getBean;
import static com.nf.mvc.support.WebTypeConverters.convert;
import static com.nf.mvc.util.ReflectionUtils.getAllSetterMethods;
import static com.nf.mvc.util.StringUtils.uncapitalize;

/**
 * 此类是一个POJO类的参数解析器，POJO类的定义由{@link ClassUtils#isPojo(Class)}决定
 * 此类并没有使用在框架中，只是一个简化版本的{@link BeanMethodArgumentResolver},
 * 只支持对POJO类内部的简单类型属性进行赋值处理，也不支持POJO类型的嵌套属性处理
 *
 * @see BeanMethodArgumentResolver
 * @see ClassUtils
 */
public class PojoMethodArgumentResolver implements MethodArgumentResolver {
    @Override
    public boolean supports(MethodParameter parameter) {
        return ClassUtils.isPojo(parameter.getType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, HttpServletRequest request) throws Exception {
        Class<?> type = parameter.getType();
        Object instance = getBean(type);

        List<Method> methods = getAllSetterMethods(type);
        for (Method method : methods) {
            //setAge方法名，属性名就是age
            String propName = uncapitalize(method.getName().substring(3));
            Object value = convert(request.getParameter(propName), method.getParameters()[0].getType());
            method.invoke(instance, value);
        }
        return instance;
    }

}
